package ch3.queue.sq;

class SqQueueClass<E> {         //非循环队列泛型类
    final int MaxSize = 100;    //假设容量为100
    private E[] data;           //存放队列中的元素
    private int front, rear;    //队头队尾指针
    public SqQueueClass() {     //构造方法
        data = (E[]) new Object[MaxSize];
        front = -1;
        rear = -1;
    }
    //队列的基本运算算法

    public boolean empty() {    //判断队列是否为空
        return front == rear;
    }

    public void push(E e) {         //元素no进队
        if (rear == MaxSize - 1) {  //队满
            throw new IllegalArgumentException("队满");
        }
        //rear++;
        data[++rear] = e;
    }

    public E pop() {    //出队元素
        if (empty()) {  //队空
            throw new IllegalArgumentException("队空");
        }
        //front++;
        return (E) data[++front];
    }

    public E peek() {   //取队头元素
        if (empty()) {  //队空
            throw new IllegalArgumentException("队空");
        }
        return (E) data[front + 1];
    }

    @Override
    public String toString() {  //非基本运算，调试用
        String ans = "";
        if (!empty()) {
            int p = front;
            do {
                p++;
                ans += data[p] + " ";
            } while (p != rear);
        }
        return ans;
    }
    public static void main(String[] args) {
        //测试1
        System.out.println("*******测试1****************");
        Integer[] a = {1, 2, 3, 4, 5};
        SqQueueClass<Integer> qu1 = new SqQueueClass<Integer>();
        for (int i = 0; i < a.length; i++) {
            qu1.push(a[i]);
            System.out.println("进队元素: " + a[i]);
        }
        System.out.println("qu1为空: " + qu1.empty());
        System.out.println("qu1: " + qu1);
        System.out.println("队头元素: " + qu1.peek());
        Integer e;
        while (!qu1.empty()) {
            e = qu1.pop();
            System.out.println("出队元素: " + e);
        }
        System.out.println("qu1: " + qu1);
        System.out.println("qu1为空: " + qu1.empty());

        //测试2
        System.out.println("*******测试2****************");
        String[] b = {"a", "b", "c", "d"};
        SqQueueClass<String> qu2 = new SqQueueClass<>();
        for (int i = 0; i < b.length; i++) {
            qu2.push(b[i]);
            System.out.println("进队元素: " + b[i]);
        }
        System.out.println("qu2为空: " + qu2.empty());
        System.out.println("qu2: " + qu2);
        String x;
        while (!qu2.empty()) {
            x = qu2.pop();
            System.out.println("出队元素: " + x);
        }
        System.out.println("qu2: " + qu2);
        System.out.println("qu2为空: " + qu2.empty());
    }
}
